package com.example.mine_platform.config;


import com.example.mine_platform.pojo.entities.User;
import com.example.mine_platform.service.UserService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");  //同源策略
        response.setHeader("Access-Control-Allow-Methods", "*");

        //从请求头中获取token
        String url = request.getRequestURL().toString();
        log.info("url:{}",url);
        String token = request.getHeader("token");

        //校验令牌
        try {
            log.info("jwt令牌为:{}",token);
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = Integer.valueOf(claims.get("id").toString());
            log.info("用户id为:{}",id);
            String phone = claims.get("phone").toString();
            log.info("用户手机号为:{}",phone);
            String level = claims.get("level").toString();
            log.info("用户权限为:{}",level);
            //放行
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败");
            response.setStatus(401);//没有访问权限
            return false;
        }
    }

}
